package com.huterox.linuxrember.Activity;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.huterox.linuxrember.Dao.AdditionDBEngine;
import com.huterox.linuxrember.R;
import com.huterox.linuxrember.utils.CircleProgressView;
import com.huterox.linuxrember.utils.FileUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;


public class AddCommandActivity extends AppCompatActivity {


    private Button bt_exit;
    private Button bt_confirm;
    private String filePath;
    private AdditionDBEngine additionDBEngine;
    private TextView txt;
    private PogTask pogTask;
    private boolean isProcessing = false;
    private CircleProgressView circleProgressView;

    String[] permissions = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.MANAGE_EXTERNAL_STORAGE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_command);
        additionDBEngine = new AdditionDBEngine(this);
        requestPermission(this);
        initView();
    }

    public void MainAction(View view, int id) {//跳转到主界面
        Intent intent = new Intent(this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt("id", id);
        intent.putExtras(bundle);
        startActivity(intent);
    }


    //初始化
    private void initView() {
        pogTask = new PogTask();
        txt = findViewById(R.id.txt);
        circleProgressView = findViewById(R.id.cirt);
        bt_exit = findViewById(R.id.bt_exit);
        bt_confirm = findViewById(R.id.bt_confirm);
        //设置监听
        AddCommandActivity.MyOnClickListener l = new AddCommandActivity.MyOnClickListener();
        bt_exit.setOnClickListener(l);
        bt_confirm.setOnClickListener(l);

    }

    /*
     * 打开文件管理器之后，选择文件返回之后负责对获取的文件路径进行处理
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
                filePath = uri.getPath();
                return;
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
                //4.4以后
                filePath = FileUtil.getPath(this, uri);

            } else {//4.4以下下系统调用方法
                filePath = FileUtil.getRealPathFromURI(this, uri);
            }
        }

        if (filePath == null) {
            Toast.makeText(AddCommandActivity.this, "未选择任何文件！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (filePath.contains(".csv")) {
            //开启异步任务，这里我们取个巧，使用pogTask来实现这个功能
            if(pogTask == null){
                pogTask = new PogTask();
            }
            pogTask.execute();
        } else {
            Toast.makeText(AddCommandActivity.this, "请检查文件是否为csv文件", Toast.LENGTH_SHORT).show();
        }
    }


    private class MyOnClickListener implements View.OnClickListener {

        Intent intent = getIntent();
        //获取当前用户点击的id
        int id = intent.getExtras().getInt("id");

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.bt_exit:
                    MainAction(view, id);
                    break;
                case R.id.bt_confirm:

                    if(!isProcessing){
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//                    设置读取文件类型为csv
                        intent.setType("application/csv");
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        startActivityForResult(intent, 0);
                    }else {
                        Toast.makeText(AddCommandActivity.this, "请等待当前任务完成", Toast.LENGTH_SHORT).show();
                    }
            }
        }
    }

    private void readCsv(String s) {


        try {
            isProcessing = true;
            File csv = new File(s);   // CSV文件路径
            BufferedReader br = new BufferedReader(new FileReader(csv));
            br.readLine();
            String line = "";
            //读取csv文件
            ArrayList<String[]> buffers = new ArrayList<>();
            while ((line = br.readLine()) != null) {
                /*
                 *  csv格式每一列内容以逗号分隔,因此要取出想要的内容,以逗号为分割符分割字符串即可,
                 *  把分割结果存到到数组中,根据数组来取得相应值
                 */
                String[] buffer = line.split(",");// 以逗号分隔
                buffers.add(buffer);

            }
            br.close();
            double current_index = 0;
            double percentage = 0.0;
            int size = buffers.size();
            //在这里将csv文件写入sqlLite数据库
            circleProgressView.setProgress(0);
            for(String[] buffer:buffers){
                current_index+=1;
                try {
                    additionDBEngine.insertCommand8(getWindow().getDecorView(), buffer[0],
                            buffer[1], buffer[2], buffer[3], buffer[4]
                    );
                } catch (ArrayIndexOutOfBoundsException ignored) {}
                //写入当前的进度条
                percentage = (current_index/size)*100;
                txt.setText((int) percentage+"%");
                circleProgressView.setProgress((int) percentage);
//                这个我们跑慢一点儿
                Thread.sleep(20);
            }



            circleProgressView.setProgress(100);
            txt.setText("导入完成");
            isProcessing = false;

        } catch (IOException ioException) {
            ioException.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


    private void requestPermission(Context context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // 判断有没有权限
            if (Environment.isExternalStorageManager()) {

            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                startActivityForResult(intent, 111);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 判断有没有权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 111);
            }
        }
    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 111) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            }
        }
    }


    private class PogTask extends AsyncTask<Void, Integer, String> {
        @Override
        //执行线程任务的页面操作，
        protected void onPreExecute() {
            super.onPreExecute();
        }
        @Override
        //不能处理UI操作,处理耗时操作（接受输入参数，返回线程执行结果）
        protected String doInBackground(Void... voids) {
            //完成任务
            readCsv(filePath);
            return null;
        }
    }

}